package com.itheima.service.impl;

import com.itheima.common.utils.POIUtils;
import com.itheima.mapper.OrderSettingMapper;
import com.itheima.pojo.OrderSetting;
import com.itheima.pojo.VO.OrderSettingVO;
import com.itheima.service.OrderSettingService;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderSettingServiceImpl implements OrderSettingService {

    private POIUtils poiUtils;
    @Autowired
    private OrderSettingMapper orderSettingMapper;

    @Override
    public void exportTemplate(String filename, HttpServletResponse response) {

        // 2. 设置响应头（必须在获取流之前设置）
        response.setHeader("content-disposition", "attachment;filename=" + filename);
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        try (
                InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("templates/" + filename);
                XSSFWorkbook excel = new XSSFWorkbook(inputStream);
                ServletOutputStream out = response.getOutputStream();
                ){

            excel.write(out);
            out.flush();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    @Override
    public void editNumberByOrderDate(OrderSetting orderSetting) {
        LocalDate localDate = orderSetting.getOrderDate().toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
        orderSettingMapper.editNumberByOrderDate(orderSetting.getNumber(), localDate);
    }

    @Override
    public List<OrderSettingVO> getOrderSettingByMonth(String month) {

        // 定义格式（允许单数字月份）
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M");
        // 解析月份为 YearMonth（格式必须为 yyyy-MM）
        YearMonth yearMonth = YearMonth.parse(month, formatter);

        // 获取当月首日和最后一日
        LocalDate begin = yearMonth.atDay(1);
        LocalDate end = yearMonth.atEndOfMonth();
        List<OrderSetting> list = orderSettingMapper.getOrderSettingByMonth(begin, end);
        List<OrderSettingVO> result = list.stream().map(orderSetting -> {
            LocalDate localDate = orderSetting.getOrderDate().toInstant()
                    .atZone(ZoneId.systemDefault()) // 或指定时区，如 ZoneId.of("UTC")
                    .toLocalDate();
            return new OrderSettingVO(localDate.getDayOfMonth(), orderSetting.getNumber(), orderSetting.getReservations());
        }).collect(Collectors.toList());
        return result;
    }

    @Transactional
    @Override
    public void importExcel(MultipartFile excelFile) throws Exception{

        // 校验文件
        poiUtils.checkFile(excelFile);
        // 获得excel数据
        List<String[]> list = poiUtils.readExcel(excelFile);

        // 1. 创建 SimpleDateFormat 实例，指定格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

        // 2. 设置严格解析模式（拒绝无效日期）
        sdf.setLenient(false);
        if (list != null && list.size() > 0) {
            for (String[] strings : list) {
                OrderSetting orderSetting = new OrderSetting();
                orderSetting.setOrderDate(sdf.parse(strings[0]));
                orderSetting.setNumber(Integer.parseInt(strings[1]));
                orderSettingMapper.insert(orderSetting);
            }
        }

    }
}
